package com.dev.op.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dev.op.entity.User;
import com.dev.op.entity.UserRole;
import com.dev.op.entity.Role;
import com.dev.op.service.RoleService;
import com.dev.op.service.UserRoleService;
import com.dev.op.mapper.UserRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
* @author Administrator
* @description 针对表【user_role】的数据库操作Service实现
* @createDate 2025-03-29 17:34:04
*/
@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole>
    implements UserRoleService{

    @Autowired
    RoleService roleService;

    @Autowired
    UserRoleMapper userRoleMapper;

    @Override
    public List<UserRole> getUserRolesByUserId(String userId) {
        QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        return this.list(queryWrapper);
    }

    @Override
    @Transactional
    public Boolean grantUserRolesByRolesId(String userId, List<String> roleIds) {
        List<Role> roles = roleService.list(new QueryWrapper<Role>().in("role_id", roleIds));
        List<UserRole> userRoles = new ArrayList<UserRole>();
        for(Role role : roles) {
            UserRole userRole = new UserRole(String.valueOf(role.getRoleId()),userId,role.getRoleName());
            userRoles.add(userRole);
        }
        return this.saveBatch(userRoles);
    }

    @Override
    @Transactional
    public Boolean grantUserRolesByRolesName(String userId, List<String> roleNames) {
        List<Role> roles = roleService.list(new QueryWrapper<Role>().in("role_name", roleNames));
        List<UserRole> userRoles = new ArrayList<UserRole>();
        for(Role role : roles) {
            UserRole userRole = new UserRole(String.valueOf(role.getRoleId()),userId,role.getRoleName());
            userRoles.add(userRole);
        }
        return this.saveBatch(userRoles);
    }

    @Override
    public List<User> getAdminUsers(int page,int size) {
        if(page <= 0 || size <= 0) {
            return null;
        }
        int offset = (page - 1) * size;
        return userRoleMapper.getUsersByRoleId(offset,size,1);
    }

    @Override
    public List<User> getTeachers(int page, int size) {
        if(page <= 0 || size <= 0) {
            return null;
        }
        int offset = (page - 1) * size;
        return userRoleMapper.getUsersByRoleId(offset,size,2);
    }
}




